<?php

namespace app\index\controller;

use think\Controller;
use think\Cookie;
use think\Session;

class User extends Controller
{
    public $ip;
    public function _initialize()
    {
//        获取客户端ip地址
        $request = request();
        $ip = $request->ip();
        $this->ip = str_replace('.','',$ip);
    }

    public function index()
    {
        if (Cookie::has('uid')) {
            $this->redirect('index/index');
        }
        //print_r(cookie('mobile'));exit;
        return $this->fetch();
    }

    public function reg()
    {
        if (Cookie::has('uid')) {
            $this->redirect('index/index');
        }
//        2018年7月23日14:31:58修改
        $invcode = input('invcode');
        // print_r(Session::get('13810758191_reg'));  exit;
        $pid =input('pid');
        if ($pid) {
            $pid = input('pid');
        }else{
            $pid=0;
        }
        $this->assign('invcode',$invcode);
        $this->assign('pid', $pid);
        return $this->fetch();
    }
    //注册用户
    public function user_reg()
    {
        if (request()->isPost()) {
            $data = input('post.');
            $user = model('User');
            $pid = 0;
            if (input('pid')) {
                $pid = input('pid');
            }
            $datas = [];
            if (!preg_match("/^1[34578]{1}\d{9}$/", $data['username'])) {
                return $this->result('', 1, '手机号码格式错误');
            }
            if ($user->mobileIsExists($data['username'])) {
                return $this->result('', 1, '该手机号已注册');
            }
            if (empty($data['password']) || empty($data['repassword'])) {
                return $this->result('', 1, '两次密码输入不一致');
            }
/*            if (Session::get($data['username'] . '_reg', 'reg') != $data['verycode']) {
                return $this->result(Session::get($data['username'] . '_reg', 'reg'), 1, '验证码错误');
            }*/
//            2018年7月23日14:13:58 修改加入邀请码
            if(isset($data['invcode'])){
                $code = $data['invcode'];
               $res = $this->invcode($code);
               if($res){
                   $pid = $res['id'];
                }else{
                    return $this->result('',1,'邀请码不正确');
                }
            }
            $datas = [
                'mobile' => $data['username'],
                'pwd' => md5($data['password']),
                'mobile' => $data['username'],
                'addtime' => time(),
                'pid' => $pid
            ];
            $res = $user->insertGetId($datas);
            if ($res) {
//               获取三级分销关系
                $user->userprofit($res);
                Session::delete($data['username'] . '_reg');
                return $this->result('', 0, '注册成功');
            } else {
                return $this->result('', 1, '注册失败');
            }
        }
    }

    /**
     * 验证邀请码是否正确
     */
    public function invcode($code){
      $res = db('user')->where('invcode',$code)->find();
      if($res){
          return $res;
      }else{
          return false;
      }
    }

    //获取注册验证码
    public function getRegCode()
    {
        if (request()->post()) {
            $data = input('mobile');
            $user = model('User');
            if (empty($data)) {
                return $this->result('', 1, '手机号不能为空');
            }
            if (!preg_match("/^1[34578]{1}\d{9}$/", $data)) {
                return $this->result('', 1, '手机号格式不正确');
            }
//            限制每天同一号码发送验证码次数
              $this->phonetimes($data);
            // 限制同一ip地址发送次数
              $this->iptimes($this->ip);
              if(cookie($data . "times")['mtimes']>5 || cookie($this->ip . '_times')>10){
                  return $this->result('',1,'超过当天发送次数限制');
              }
              $code = $this->GetRandStr();
//            注册验证码
            $type = 0;
            $res = sendcode($data,$code,$type);
            if($res['status'] == 'success'){
                Session::set($data . '_reg', $code, 'reg');
                $this->result('',1,'发送成功');
            }else{
                $this->result('',0,'发送失败,请重新发送');
            }
//            return $this->result(session($data . '_reg'), 0, '发送成功');
        }
    }

    public function phonetimes($mobile)
    {
       $times = cookie($mobile . 'times');
       $data = [
           'mobile' => $mobile,
           'mtimes' => 1,
       ];
//       过期时间
       $time = strtotime(date('Y-m-d') . "23:59:59")-time();
       if(!$times){
           cookie($mobile. 'times',$data,$time);
       }else{
           $times['mtimes'] += 1;
           cookie($mobile . 'times',$times,$time);
       }
    }

    public function iptimes($ip)
    {
        $times = cookie($ip . '_times');
//       过期时间
        $time = strtotime(date('Y-m-d') . "23:59:59") - time();
        if($times){
            $times += 1;
            cookie($ip . '_times',$times,$time);
        }else{
            cookie($ip . '_times',1,$time);
        }
    }

    //登陆验证
    public function checkLogin()
    {
        if (Cookie::has('uid')) {
            return $this->result('', 0, '您已登陆');
        }
        if (request()->isPost()) {
            $data = input('post.');
            $user = model('User');
            $datas = [];
            if (!preg_match("/^1[34578]{1}\d{9}$/", $data['username'])) {
                return $this->result('', 1, '手机号码格式错误');
            }
            if (empty($data['password'])) {
                return $this->result('', 1, '密码不能为空');
            }
            if (!$user->mobileIsExists($data['username'])) {
                return $this->result('', 1, '账户不存在');
            }

            $res = $user->where(array('mobile' => $data['username']))->find();
            if ($res['pwd'] == md5($data['password'])) {
                cookie('mobile', $res['mobile']);
                cookie('uid', $res['id']);
                return $this->result('', 0, '登陆成功');
            } else {
                return $this->result('', 1, '账号或密码错误');
            }
        }
    }
    //检查用户是否存在
    public function mobile_exist()
    {
        $mobile = input('mobile');
        $user = model('User')->mobileIsExists($mobile);
        if (!$user) {
            return $this->result('', 1, '手机号码不存在');
        } else {
            return $this->result('', 0);
        }
    }


    //获取修改密码验证码
    public function getRepwdCode()
    {
        if (request()->post()) {
            $data = input('mobile');
            $codelog=model('Codelog');
            $sendCode=$this->GetRandStr();

            if (empty($data)){
                return $this->result('', 1, '手机号不能为空');
            }
            if (!preg_match("/^1[34578]{1}\d{9}$/", $data)) {
                return $this->result('', 1, '手机号格式不正确');
            }
            //            修改密码验证码
            $type = 1;
            $result = sendcode($data,$sendCode,$type);
            if($result['status'] == 'success'){
                Session::set($data . '_changepwd',$sendCode,'reg');
                return $this->result('',0,'已成功发送手机验证码');
            }else{
                return $this->result('',1,'发送失败');
            }

            /*//判断是否存在存在有效验证码
            $hascode=$codelog->hasCode($data,1);
            if($hascode){
                $sendCode=$hascode['code'];
                //1.发送验证码
                //2.返回提示
                if($sendCode){
                    return $this->result('', 0, '发送成功,发送已存在验证码');
                }else{
                    return $this->result('', 1, '发送失败');
                }
            }else{
                $res=$codelog->addMsgCode($data,$sendCode,1);
                //发送验证码
                if($res){
                    return $this->result('', 0, '发送成功，发送新增验证码');
                }else{
                    return $this->result('', 1, '发送失败');
                }
            }*/

        }
    }

    public function repwd()
    {
        return $this->fetch();
    }

    //验证手机验证码
    public function verifycode(){
        if(request()->isPost()){
            $data=input('post.');
            $codelog=model('Codelog');
            if(empty($data['username'])||empty($data['code'])||empty($data['code_type'])){
                return $this->result('',1,'信息输入有误');
            }
            if (!preg_match("/^1[34578]{1}\d{9}$/", $data['username'])){
                return $this->result('', 1, '手机号码格式错误');
            }
            if(!preg_match('/^\d+$/i', $data['code'])){
                return $this->result('', 1, '验证码必须为数字格式');
            }
            if(Session::get($data['username'] . '_changepwd') !== $data['code']){
                return $this->result('',1,'验证码输入错误');
            }

            return $this->result('',0,'验证成功');
/*            $where=[
                'mobile'=>$data['username'],
                'code'=>$data['code'],
                'code_type'=>$data['code_type'],
                'status'=>0,
                 'add_time'=>['gt',time()-60],
            ];
            $res=$codelog->where($where)->find();*/
            /*if($res){
                if($res['code']==$data['code']){
                    return $this->result('', 0, '验证成功');
                }else{
                    return $this->result('', 1, '验证码错误2');
                }

            }else{
                return $this->result('', 1, '验证码错误1');
            }*/
        }
    }

    //重制密码
    public function reset(){
        if(request()->isPost()){
            $data=input('post.');
            if(empty($data['username'])||empty($data['password'])||empty($data['repassword'])){
                return $this->result('',1,'请填写完整信息');
            }
            if (!preg_match("/^1[34578]{1}\d{9}$/", $data['username'])){
                return $this->result('', 1, '手机号码格式错误');
            }
            if($data['password']!=$data['repassword']){
                return $this->result('',1,'两次密码输入不一致');
            }
            $user=model('User');
            $res=$user->where('mobile',$data['username'])->update(array('pwd'=>md5($data['password'])));
            if($res){
                return $this->result('',0,'修改成功');
            }else{
                return $this->result('',1,'修改失败');
            }

        }
    }

    /**
     * 退出登录
     * @param int $length
     * @return string
     */
    public function loginout(){
        cookie('uid',null);
        return $this->redirect('user/index');
    }

    //获取随机数
    private function GetRandStr($length = 4)
    {
        return str_pad(mt_rand(0, pow(10, $length) - 1), $length, '0', STR_PAD_LEFT);
    }

}